package com.cedric.component;

import com.cedric.handler.DelayJobHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

/**
 * @program: delay-queue
 * 轮询处理
 * @description: 设置了线程池为每个bucket设置一个轮询操作
 * @author: 史偕成
 * @create: 2021/09/26 21:39
 **/
@Component
public class DelayTimer implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private DelayBucket delayBucket;
    @Autowired
    private JobPool jobPool;
    @Autowired
    private ReadyQueue readyQueue;

    @Value("${thread.size}")
    private int length;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        ExecutorService executorService = new ThreadPoolExecutor(
                length,
                length,
                0L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());

        for (int i = 0; i < length; i++) {
            executorService.execute(new DelayJobHandle(delayBucket, jobPool, readyQueue, i));
        }
    }
}
